package com.gz.moreaseManager.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 请求包装对象 处理Xss
 */
public class XssWrapper extends HttpServletRequestWrapper {

	public XssWrapper(HttpServletRequest request) {
		super(request);
	}

	/**
	 * 覆盖getParameter方法，将参数名和参数值都做XSS过滤
	 */
	@Override
	public String getParameter(String name) {
		String value = super.getParameter(xssEncode(name));
		if (value != null)
			value = xssEncode(value);
		return value;
	}

	/**
	 * 覆盖getParameterValues方法，将参数名和参数值都做XSS过滤
	 */
	public String[] getParameterValues(String parameter) {
		String[] values = super.getParameterValues(parameter);
		if (values == null) return null;
		int count = values.length;
		String[] encodedValues = new String[count];
		for (int i = 0; i < count; i++) {
			encodedValues[i] = xssEncode(values[i]);
		}
		return encodedValues;
	}

	/**
	 * 获取request的属性时，做XSS过滤
	 */
	@Override
	public Object getAttribute(String name) {
		Object value = super.getAttribute(name);
		if (null != value && value instanceof String) {
			value = xssEncode((String) value);
		}
		return value;
	}

	/**
	 * 覆盖getHeader方法，将参数名和参数值都做XSS过滤。
	 */
	@Override
	public String getHeader(String name) {
		String value = super.getHeader(xssEncode(name));
		if (value != null) {
			value = xssEncode(value);
		}
		return value;
	}

	/**
	 * 将容易引起XSS漏洞的半角字符直接替换成全角字符
	 */
	private static String xssEncode(String str) {
		if (str == null || str.isEmpty()) {
			return str;
		}
		HTMLFilter htmlFilter = new HTMLFilter();
		return htmlFilter.filter(str);
	}
}